<template>
  <GcTable
    v-loading="loading"
    v-model:searchKeywords="searchKeywords"
    :pagination="pagination"
    :columns="STAFF_MANAGE_COLUMNS"
    :tableData="tableData"
    :filterList="filterList"
    :defaultFilter="defaultFilter"
    @selection-change="handlerSelectionChange"
    searchPlaceholder="请输入用户名/昵称进行搜索"
    @current-change="handlerCurrentChange"
    @search="handlerSearch"
    @get-search-params="getSearchParams"
    @reset-fileds="resetSearchParams">
    <template #btn-group>
      <el-button
        v-permission="'staff-manage-permission:btn:add'"
        type="primary"
        @click="currentStaff = null; staffModalVisible = true">新增员工</el-button>
      <el-button
        v-permission="'staff-manage-permission:btn:delete'"
        @click="deleteStaff(selectionIds)"
        :disabled="!selectionIds.length"
        type="danger">批量删除</el-button>
    </template>
    <template #gender="{ row }">{{ row.gender === '0' ? '女' : row.gender === '1' ? '男' : '未知' }}</template>
    <template #avatar="{ row }">
      <el-image
        v-if="row.avatar"
        :z-index="999999"
        preview-teleported
        style="width: 30px; height: 30px"
        :src="row.avatar"
        :zoom-rate="1.2"
        :preview-src-list="[row.avatar]"
        fit="cover"
      />
    </template>
    <template #role="{ row }">
      <GcToolTip :content="row.roleNames.join('，')" />
    </template>
    <template #status="{ row }">
      <el-switch
        :disabled="!hasPermission('staff-manage-permission:btn:edit')"
        :key="row.id"
        v-model="row.status"
        active-value="1"
        inactive-value="0"
        active-text="启用"
        inactive-text="禁用"
        inline-prompt
        :width="52"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        @change="handlerUpdateStatus($event, row)"
      />
    </template>
    <template #operate="{ row }">
      <div class="operate-btn-group center">
        <gc-icon-button
          v-permission="'staff-manage-permission:btn:edit'"
          type="link"
          @click="updateStaff(row)">编辑</gc-icon-button>
        <gc-icon-button
          v-permission="'staff-manage-permission:btn:delete'"
          type="link"
          @click="deleteStaff([row.id])">删除</gc-icon-button>
        <gc-icon-button
          v-permission="'staff-manage-permission:btn:change-password'"
          type="link"
          @click="currentStaff = row; passwordVisible = true">修改密码</gc-icon-button>
      </div>
    </template>
  </GcTable>
  <OperateStaffModal
    v-if="staffModalVisible"
    @close-modal="closeModal"
    :staffInfo="currentStaff" />

  <ChangePassword
    v-if="passwordVisible"
    @close-modal="closeModal"
    :isSelf="false"
    :username="currentStaff?.username" />
</template>

<script setup lang="ts" name="StaffManage">
import { ref, reactive } from 'vue'
import { hasPermission } from '@/directives/permission'
import { STAFF_MANAGE_COLUMNS } from './const'
import usePagination from '@/hooks/usePagination'
import type { Staff } from '@/http/type'
import type { Pagination } from '@/@type'
import { apiGetStaffList, apiBatchDeleteStaff, apiUpdateStaffStatus } from '@/http/service'
import OperateStaffModal from './components/OperateStaffModal.vue'
import ChangePassword from '@/components/ChangePassword.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

interface ResponseStaff extends Pagination {
  dataList: Array<Staff>
}
interface AdvanceSearch {
  username: string
  nickname: string
  status: string
  email: string
  tel: string
}

const staffModalVisible = ref(false)
const passwordVisible = ref(false)
const selectionIds = ref<Array<number>>([])
const { pagination, loading } = usePagination()
const tableData = ref<Array<Staff>>([])
const searchKeywords = ref('')
const filterList = [
  {
    name: '用户名',
    key: 'username',
    type: 'input' as const,
    placeholder: '请输入用户名（模糊搜索）'
  },
  {
    name: '昵称',
    key: 'nickname',
    type: 'input' as const,
    placeholder: '请输入邮箱（模糊搜索）'
  },
  {
    name: '邮箱',
    key: 'email',
    type: 'input' as const,
    placeholder: '请输入邮箱（模糊搜索）'
  },
  {
    name: '手机号',
    key: 'tel',
    type: 'input' as const,
    placeholder: '请输入手机号（模糊搜索）'
  },
  {
    name: '状态',
    key: 'status',
    type: 'select' as const,
    placeholder: '请选择员工状态',
    options: [
      { value: '0', label: '禁用' },
      { value: '1', label: '启用' }
    ]
  }
]
const defaultFilter = reactive<AdvanceSearch>({
  username: '',
  nickname: '',
  status: '',
  email: '',
  tel: ''
})
const currentStaff = ref<null | Staff>(null)

/**
 * 员工列表查询
 */
async function findStaffList () {
  const searchParams = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    searchKeywords: searchKeywords.value,
    ...defaultFilter
  }
  loading.value = true
  try {
    const { dataList, ...pageInfo } = await apiGetStaffList<ResponseStaff>(searchParams)
    tableData.value = dataList
    Object.assign(pagination, pageInfo)
  } catch (error) {
    tableData.value = []
  } finally {
    loading.value = false
  }
}
findStaffList()

function updateStaff (currentItem: Staff) {
  currentStaff.value = currentItem
  staffModalVisible.value = true
}

function handlerSelectionChange (selections: Array<Staff>) {
  selectionIds.value = selections.map(o => o.id)
}

/**
 * 批量删除员工
 * @param ids
 */
async function deleteStaff (ids: Array<number>) {
  await ElMessageBox.confirm(
    '删除员工账号无法恢复，确认删除？',
    '提示',
    {
      type: 'warning'
    }
  )
  await apiBatchDeleteStaff({ ids })
  ElMessage.success('删除员工成功')
  pagination.pageNo = 1
  findStaffList()
}

/**
 * 更新员工账号状态
 * @param status
 * @param row
 */
async function handlerUpdateStatus (status: string, row: Staff) {
  if (row.id) {
    try {
      await apiUpdateStaffStatus({ id: row.id, status })
    } catch (error) {
      row.status = status === '1' ? '0' : '1'
    }
  }
}

function handlerSearch () {
  pagination.pageNo = 1
  findStaffList()
}

function handlerCurrentChange (val: number) {
  pagination.pageNo = val
  findStaffList()
}

function getSearchParams (searchParams: AdvanceSearch) {
  Object.assign(defaultFilter, searchParams)
  findStaffList()
}

function resetSearchParams (searchParams: AdvanceSearch) {
  searchKeywords.value = ''
  Object.assign(defaultFilter, searchParams)
  findStaffList()
}

function closeModal (update?: boolean) {
  if (update) {
    findStaffList()
  }
  staffModalVisible.value = false
  passwordVisible.value = false
}
</script>

<style lang="scss" scoped></style>
